import React, { Component } from 'react'

import { SearchBar } from 'antd-mobile'

import { getCity } from '../../../utils'

import API from '@/utils/api'

import styles from './index.module.css'

export default class Search extends Component {
  // 当前城市id
  cityId = getCity().value

  //接受定时器的id
  timeId=null

  state = {
    // 搜索框的值
    searchTxt: '',
    tipsList: []
  }

  // 渲染搜索结果列表
  renderTips = () => {
    const { tipsList } = this.state

    return tipsList.map(item => (
      <li key={item.community} className={styles.tip} onClick={()=>this.onTipsClick(item)}>
        {item.communityName}
      </li>
    ))
  }

  onTipsClick(item){
    const { history } = this.props
    const { community, communityName } = item
    history.push('/rent/add',{id: community,name: communityName})
  }
  
  //搜索框输入改变事件
  handleSearchTxt=(value)=>{
    this.setState({
      searchTxt: value
    })

    clearTimeout(this.timeId)

    if(!value.trim()){
      return  this.setState({ tipsList: [] })
    }

    this.timeId=setTimeout(async ()=>{
      const res=await API.get('/area/community',{params:{name: value,id: this.cityId}})
      console.log(res);
      this.setState({
        tipsList: res.data.body
      })
    },500)
  }

  render() {
    const { history } = this.props
    const { searchTxt } = this.state

    return (
      <div className={styles.root}>
        {/* 搜索框 */}
        <SearchBar
          placeholder="请输入小区或地址"
          value={searchTxt}
          showCancelButton={true}
          onChange={this.handleSearchTxt}
          onCancel={() => history.replace('/rent/add')}
        />
        {/* 搜索提示列表 */}
        <ul className={styles.tips}>{this.renderTips()}</ul>
      </div>
    )
  }
}
